// src/pages/task/schedule/index.tsx - 任务计划页面
import React, {useState, useEffect} from 'react';
import {message, Form} from 'antd';
import { 
  getScheduleList, 
  createSchedule, 
  updateSchedule, 
  deleteSchedule, 
  startSchedule 
} from '@/api/task';
import ScheduleHeader from './components/ScheduleHeader';
import ScheduleTable from './components/ScheduleTable';
import ScheduleModal from './components/ScheduleModal';
import {ScheduleItem, ScheduleCreateForm} from './types';

const SchedulePage: React.FC = () => {
  const [schedules, setSchedules] = useState<ScheduleItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [modalMode, setModalMode] = useState<'create' | 'edit'>('create');
  const [editingRecord, setEditingRecord] = useState<ScheduleItem | null>(null);
  const [pagination, setPagination] = useState({
    page: 1,
    pageSize: 10,
    total: 0,
  });
  const [form] = Form.useForm();

  // 获取任务计划列表
  const fetchSchedules = async (page: number = 1, pageSize: number = 10) => {
    setLoading(true);
    try {
      const res = await getScheduleList(page, pageSize);

      setSchedules(res?.data?.items || []);
      setPagination({
        page: page,
        pageSize: pageSize,
        total: res?.data?.total || 0,
      });
    } catch (error) {
      console.error('获取任务计划失败:', error);
      message.error('获取任务计划失败');
    } finally {
      setLoading(false);
    }
  };

  // 运行任务计划
  const handleRun = async (id: number, record: ScheduleItem) => {
    try {
      await startSchedule(id, record.args, record.kwargs);
      message.success('任务启动成功');
      await fetchSchedules(); // 刷新列表以更新最后运行时间
    } catch (error) {
      console.error('任务启动失败:', error);
      message.error('任务启动失败');
    }
  };

  // 处理表单提交
  const handleFinish = async (values: ScheduleCreateForm) => {
    try {
      if (modalMode === 'create') {
        // 创建新任务
        await createSchedule(values);
        message.success('创建成功');
      } else {
        // 编辑任务
        const submitData = {
          ...values,
          id: editingRecord?.id,
        };

        // 调用更新任务计划的API
        await updateSchedule(submitData);
        message.success('更新成功');
      }

      setIsModalVisible(false);
      form.resetFields();
      await fetchSchedules();
    } catch (error) {
      console.error('操作失败:', error);
      message.error(modalMode === 'create' ? '创建失败' : '更新失败');
    }
  };

  // 处理删除任务计划
  const handleDelete = async (id: number) => {
    try {
      // 调用删除任务计划的API
      await deleteSchedule(id);
      message.success('删除成功');
      await fetchSchedules();
    } catch (error) {
      console.error('删除失败:', error);
      message.error('删除失败');
    }
  };

  // 处理编辑任务计划
  const handleEdit = (record: ScheduleItem) => {
    setModalMode('edit');
    setEditingRecord(record);
    // 先重置表单
    form.resetFields();
    form.setFieldsValue({
      ...record,
    });
    setIsModalVisible(true);
  };

  useEffect(() => {
    fetchSchedules().then();
  }, []);

  const handleTableChange = (pager: any) => {
    fetchSchedules(pager.current, pager.pageSize).then();
  };

  // 自定义表单重置方法
  const resetFormFields = () => {
    form.setFieldsValue({
      name: '',
      code: '',
      description: '',
      task_type: 'normal',
      crontab: '',
      interval: '{}',
      args: '[]',
      kwargs: '{}'
      // 注意：不包含id字段，确保在重置时删除id
    });
  };

  return (
    <>
      <ScheduleHeader onAddSchedule={() => {
        setModalMode('create');
        setEditingRecord(null);
        // 使用自定义重置方法
        resetFormFields();
        setIsModalVisible(true);
      }}/>
      <ScheduleTable
        schedules={schedules}
        loading={loading}
        pagination={pagination}
        onPageChange={handleTableChange}
        onDelete={handleDelete}
        onEdit={handleEdit}
        onRun={(id, record) => handleRun(id, record)}
      />
      <ScheduleModal
        visible={isModalVisible}
        onCancel={() => {
          // 使用自定义重置方法
          resetFormFields();
          // 关闭模态框
          setIsModalVisible(false);
        }}
        onOk={() => form.submit()}
        form={form}
        onFinish={handleFinish}
        mode={modalMode}
        initialValues={editingRecord || undefined}
      />
    </>
  );
};

export default SchedulePage;